package notifier

import (
	"bgs/cache/redisImp"
	"bgs/conf"
	"bgs/db"
	"bgs/util"
	wxpMinaService "bgs/wxp/mina"
	"context"
	// "fmt"

	"go.uber.org/zap"
)

// Notifier 通知组件
type Notifier struct {
	slog           *zap.SugaredLogger
	wxpMinaService *wxpMinaService.MinaServiceImp
	chans          []chan *wxpMinaService.SendNotifyParam
	// chansTest      []chan int
	Ready bool
}

// NewNotifier initialization
func NewNotifier(
	notifierConf conf.NotifierSection,
	wechatConfPtr *conf.WechatSection,
	slog *zap.SugaredLogger,
	pgdao *db.PgDao,
	vars *conf.VarsSection,
	adp *cache.Adapter,
) (n *Notifier, err error) {
	n = &Notifier{
		slog:           slog,
		wxpMinaService: wxpMinaService.NewMinaService(pgdao, slog, wechatConfPtr, vars, adp),
	}
	n.chans = n.runWorkers(notifierConf.Worker)
	// n.chansTest = n.runWorkersTest(notifierConf.Worker)
	n.Ready = true
	return
}

func (n *Notifier) runWorkers(max uint32) (chans []chan *wxpMinaService.SendNotifyParam) {
	for i := 0; i < int(max); i++ {
		ch := make(chan *wxpMinaService.SendNotifyParam)
		n.slog.Infof("add worker:%d", i+1)
		go n.notify(ch)
		chans = append(chans, ch)
	}
	return
}

func (n *Notifier) notify(ch <-chan *wxpMinaService.SendNotifyParam) {
	ctx := context.Background()
	for sp := range ch {
		n.wxpMinaService.SendNotify(ctx, sp)
	}
	n.slog.Infof("should not reach here")
}

func (n *Notifier) GetWorker() (ch chan<- *wxpMinaService.SendNotifyParam) {
	upper := len(n.chans) - 1
	ch = n.chans[util.RandomInt(0, int32(upper))]
	if ch != nil {
		return
	}
	return
}

/*
func (n *Notifier) runWorkersTest(max uint32) (chans []chan int) {
	for i := 1; i <= int(max); i++ {
		ch := make(chan int)
		chans = append(chans, ch)
		n.slog.Infof("add workerTest:%d", i)
		go n.notifyTest(i, ch)
	}
	return
}

func (n *Notifier) notifyTest(workerNo int, ch <-chan int) {
	// ctx := context.Background()
	for i := range ch {
		fmt.Printf("notifyTest(%d) got val:%d\n", workerNo, i)
	}
	n.slog.Infof("should not reach here")
}

func (n *Notifier) GetTestWorker() (ch chan<- int) {
	upper := len(n.chansTest) - 1
	ridx := util.RandomInt(0, int32(upper))
	fmt.Printf("%d-%d\n", upper, ridx)
	ch = n.chansTest[ridx]
	if ch != nil {
		return
	}
	return
}
*/
